package com.dong;

public class Test2 {


    public static void main(String[] args) {

        Data data = new Data();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "a").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "b").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "c").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "d").start();

    }
}

class Data {

    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        System.out.println("wait方法前");
        while (number != 0) {
            //等待
            this.wait();
            System.out.println("wait方法后");
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        System.out.println("wait方法前");
        while (number == 0) {
            this.wait();
        }

        number--;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        System.out.println("wait方法后");
        this.notifyAll();
    }
}
